<?php
namespace App\Admin\Controllers\Products;

use App\Importer\Products\AmazonSku\AmazonSkuImporter;
use App\Jobs\Products\AmazonSkuSRelate;
use App\Jobs\Products\AmazonSkuUpRelate;
use App\Models\Basics\AmazonAccount;
use App\Models\Basics\SysCountry;
use App\Models\Basics\SysPlatAccount;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductSku;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Facades\DB;
class AmazonSkuUploadController extends AdminController{

    protected $title = '亚马逊产品上传';

    protected function grid()
    {
        $type = request('type');
        return view("products.amazon-sku.index",compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importAmazonSku(UploadedFile $file){
        try{
            $data = Excel::toArray(new AmazonSkuImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $items = [];
            $userId = Admin::user()->id;
            foreach($data as $row){
                $count++;
                $sku = $row[0] ? trim($row[0]) : '';
                $sellerSku = $row[1] ? trim($row[1]) : '';
                $amazonAccount = $row[2] ? trim($row[2]) : '';
                $_country = $row[3] ? trim($row[3]) : '';
                $upcType = $row[4] ? trim($row[4]) : '无';
                $upc = $row[5] ? trim($row[5]) : '无';
                $amazonPno = $row[6] ? trim($row[6]) : '';
                $pAsin = $row[7] ? trim($row[7]) : '';
                $cAsin = $row[8] ? trim($row[8]) : '';
                $fnSku = $row[9] ? trim($row[9]) : null;
                $fanEu = $row[10] ? trim($row[10]) : '非泛欧';
                if(!$sku || !$sellerSku || !$amazonAccount || !$_country || !$pAsin || !$cAsin){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $country = strtoupper($_country);
                $key = $sellerSku.'_'.$country;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                if(!in_array($upcType,ProductAmazonSku::$_barcodeType)){
                    $errors[$count] = $upcType.'不存在，请选择'.implode('、',ProductAmazonSku::$_barcodeType);
                    continue;
                }
                $upcTypeId = array_search($upcType,ProductAmazonSku::$_barcodeType);
                if($upcTypeId == 3){
                    $upc = '无';
                }
                if(!in_array($fanEu,ProductAmazonSku::$_fanEu)){
                    $errors[$count] = $fanEu.'不存在，请选择'.implode('、',ProductAmazonSku::$_fanEu);
                    continue;
                }
                $countryId = SysCountry::getIdByCountry($country);
                if(!$countryId){
                    $errors[$count] = $_country.'系统不存在';
                    continue;
                }
                $amazonAccountId = SysPlatAccount::getIdByAccount($amazonAccount);
                if(!$amazonAccountId){
                    $errors[$count] = $amazonAccount.'系统不存在';
                    continue;
                }
                $pSkuId = ProductSku::getValueByCode($sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $sku.'系统不存在';
                    continue;
                }
                $reCount = ProductAmazonSku::query()
                    ->where('seller_sku',$sellerSku)
                    ->where('country_id',$countryId)
                    ->count();
                if($reCount > 0){
                    $errors[$count] = $key.'系统已存在，需要更新请前往更新';
                    continue;
                }
                DB::beginTransaction();
                $pas = ProductAmazonSku::query()->create(
                    [
                        'seller_sku' => $sellerSku,
                        'country_id' => $countryId,
                        'psku_id' => $pSkuId,
                        'barcode_type' => $upcTypeId,
                        'barcode' => $upc,
                        'amazon_part_number' => $amazonPno,
                        'account_id' => $amazonAccountId,
                        'parent_asin' => $pAsin,
                        'child_asin' => $cAsin,
                        'fnsku' => $fnSku,
                        'fan_eu' => array_search($fanEu,ProductAmazonSku::$_fanEu),
                        'cuser_id' => $userId,
                    ]
                );
                if($pas){
                    $items[] = $pas;
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(!empty($items)){
                //添加基础备货数据
                AmazonSkuSRelate::dispatch($items,$userId);
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    //更新
    private function _importAmazonSkuUp(UploadedFile $file){
        try{
            $data = Excel::toArray(new AmazonSkuImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $items = [];
            foreach($data as $row){
                $count++;
                $sellerSku = $row[0] ? trim($row[0]) : '';
                $_country = $row[1] ? trim($row[1]) : '';
                $upcType = $row[2] ? trim($row[2]) : '';
                $upc = $row[3] ? trim($row[3]) : '';
                $amazonPno = $row[4] ? trim($row[4]) : '';
                $pAsin = $row[5] ? trim($row[5]) : '';
                $cAsin = $row[6] ? trim($row[6]) : '';
                $fnSku = $row[7] ? trim($row[7]) : '';
                $fanEu = $row[8] ? trim($row[8]) : '';
                $status = $row[9] ? trim($row[9]) : '';
                if(!$sellerSku || !$_country){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $country = strtoupper($_country);
                $key = $sellerSku.'_'.$country;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $countryId = SysCountry::getIdByCountry($country);
                if(!$countryId){
                    $errors[$count] = $_country.'系统不存在';
                    continue;
                }
                DB::beginTransaction();
                $pas = ProductAmazonSku::query()
                    ->where('seller_sku',$sellerSku)
                    ->where('country_id',$countryId)
                    ->first();
                if(!$pas){
                    $errors[$count] = $key.'系统不存在，需要新增请前往新增';
                    DB::rollBack();
                    continue;
                }
                $upcTypeId = $pas->barcode_type;
                if($upcType){
                    if(!in_array($upcType,ProductAmazonSku::$_barcodeType)){
                        $errors[$count] = $upcType.'不存在，请选择'.implode('、',ProductAmazonSku::$_barcodeType);
                        DB::rollBack();
                        continue;
                    }
                    $upcTypeId = array_search($upcType,ProductAmazonSku::$_barcodeType);
                    $pas->barcode_type = $upcTypeId;
                }
                if($upc){
                    $pas->barcode = $upcTypeId == 3 ? '无' : $upc;
                }
                if($fanEu){
                    if(!in_array($fanEu,ProductAmazonSku::$_fanEu)){
                        $errors[$count] = $fanEu.'不存在，请选择'.implode('、',ProductAmazonSku::$_fanEu);
                        DB::rollBack();
                        continue;
                    }
                    $pas->fan_eu = array_search($fanEu,ProductAmazonSku::$_fanEu);
                }
                if($amazonPno){
                    $pas->amazon_part_number = $amazonPno;
                }
                if($pAsin){
                    $pas->parent_asin = $pAsin;
                }
                if($cAsin){
                    $pas->child_asin = $cAsin;
                }
                if($fnSku){
                    $pas->fnsku = $fnSku;
                }
                if($status){
                    if(!in_array($status,ProductAmazonSku::$_status)){
                        $errors[$count] = $status.'不存在，请选择'.implode('、',ProductAmazonSku::$_status);
                        continue;
                    }
                    $pas->status = array_search($status,ProductAmazonSku::$_status);
                    if($pas->status == 2){
                        $pas->times = 0;
                    }
                }
                $flag = $pas->save();
                if($flag){
                    if($fanEu || ($pas->fan_eu == 1 && $status)){
                        $fanEuKey = $sellerSku.'_'.$pas->child_asin.'_'.$pas->fnsku;
                        if(!in_array($fanEuKey,$items)){
                            $items[] = $fanEuKey;
                        }
                    }
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(!empty($items)){
                AmazonSkuUpRelate::dispatch($items);
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
